import ReconnectingWebSocket from 'reconnecting-websocket'
import { websocketConnect } from './websocket'
/**
 *拉起程序
 * @param url
 * @param cb
 */
const launchApp = (url: string, cb: Function) => {
	/* * 浏览器行为表
    没安
      Chrome:			cb
      FF:				cb
      win10-IE11:		blur->focus->blueFocusCb
      win7-IE10:		cb

    询问
      Chrome:			blur->focus->blueFocusCb
      FF:				blur->focus->blueFocusCb （询问框非模态，用户可主动触发focus，目前不能解决）
      win10-IE11:		blur->focus->blueFocusCb

    记住
      Chrome:			cb
      FF:				cb
      win10-IE11:		cb
      win7-IE10:		cb
    * */
	let isBlue = false
	let t: NodeJS.Timeout | null = null
	let onBlue = function () {
		isBlue = true
	}

	// 0.1秒内发生了blur，则等待focus发生触发回调
	let blueFocusCb = function () {
		if (isBlue) {
			t && clearTimeout(t)
			'function' == typeof cb && cb('blueFocusCb')
		}
		isBlue = false
		window.document.removeEventListener('blur', onBlue)
		window.document.removeEventListener('focus', blueFocusCb)
	}
	window.document.addEventListener('blur', onBlue)
	window.document.addEventListener('focus', blueFocusCb)

	// 触发打开应用
	let iframeEl = document.createElement('iframe')
	iframeEl.src = url
	iframeEl.style.display = 'none'
	document.body.appendChild(iframeEl)
	setTimeout(function () {
		document.body.removeChild(iframeEl)
	}, 100)

	// 0.1秒内没有发生blur（没有询问）则回未安装或已记住都会触
	t = setTimeout(function () {
		window.document.removeEventListener('blur', onBlue)
		if (!isBlue) {
			window.document.removeEventListener('focus', blueFocusCb)
			'function' == typeof cb && cb('cb')
		}
	}, 100)
}
/**发生错误重连次数 */
const TRY_COUNT = 1
/**尝试连接拉起的次数 */
const CONNECT_COUNT = 0

let try_count = TRY_COUNT
let connect_count = CONNECT_COUNT
/**记录弹出框弹出的次数 */
let tip: null | { hide: () => void; then: (resolve: (res: boolean) => void) => Promise<void> } = null

export interface ReconnectingWebSocketProps extends ReconnectingWebSocket {}
/**
 *ws建链
 * @param url
 * @param setRws
 * @param callback
 */
const WebSocketStart = (
	url: string,
	tableUrl: string,
	setRws: (r: ReconnectingWebSocketProps | null) => void,
	callback: (message: any) => void
) => {
	let r: ReconnectingWebSocketProps = websocketConnect({
		url: url,
		config: {
			debug: false,
			reconnectionDelayGrowFactor: 0,
			connectionTimeout: 3000,
			maxRetries: TRY_COUNT, //最多连接次数
		},
		onOpen: () => {
			//连接成功，重置状态
			try_count = TRY_COUNT
			tip = null
			connect_count = 0
			setRws(r)
		},
		onError: () => {
			//再次尝试连接ws
			if (try_count > 0) {
				try_count = try_count - 1
			} else {
				//ws持续连接不成功，就尝试进行拉起操作
				//若之前没有进行拉起操作，就进行拉起操作
				if (connect_count === 0 && tableUrl) {
					launchApp(tableUrl, () => {
						setTimeout(() => {
							WebSocketStart(url, tableUrl, setRws, callback)
						}, 3000)
					})
					connect_count = connect_count + 1
				}
			}
		},
		onClose: () => {
			setRws(null)
		},
		onMessage: (evt: { data: string }) => {
			//接收消息
			let innerCodeObj = JSON.parse(evt.data)
			callback(innerCodeObj)
		},
	})
}
export { launchApp, WebSocketStart }
